local isServerAlive = true

local isLoad=false

local sqlfile= "C:/Users/Aaron/Desktop/mysql-state/mysql-proxy/sqls.txt"
local typefile= "C:/Users/Aaron/Desktop/mysql-state/mysql-proxy/types.txt"
local sqls = {}
local types = {}

function saveDataToFile(strings, filename)
    local file = io.open(filename, "w")
    if file then
        for _, str in ipairs(strings) do
            file:write(str, "\n")
        end
        file:close()
        print("Strings saved to " .. filename)
    else
        print("Error opening file for writing.")
    end
end

function readStringsFromFile(filename , isNumber)
    local file = io.open(filename, "r")
    local strings = {}

    if file then
        for line in file:lines() do
            if isNumber then
                table.insert(strings, tonumber(line))
            else
                table.insert(strings, line)
            end
        end
        file:close()
    else
        print("Error opening file for reading.")
    end

    return strings
end



function connect_server()
    proxy.connection.backend_ndx = 1
    if proxy.global.backends[1].state == proxy.BACKEND_STATE_DOWN then
        print("Server Down!")
        isServerAlive=false
        isLoad=false
    end
end



function read_query(packet)
    local type = packet:byte()
    local sql = packet:sub(2)
    if isLoad == false then
        if string.match(sql, "^CHECK") then
            sqls=readStringsFromFile(sqlfile,false)
            types=readStringsFromFile(typefile,true)
            isLoad=true
            local lastid= #sqls
            print("Try to redo the last sql:" ..sqls[lastid])
            local new_query = sqls[lastid]
            proxy.queries:append(1, string.char(types[lastid])  .. new_query)
            return types[lastid]
        end
    else
        if type == proxy.COM_QUERY then
            table.insert(types,type)
            table.insert(sqls,sql)
            print("Receive SQL: " .. string.sub(packet, 2))
            print("Save SQLs")
            saveDataToFile(sqls,sqlfile)
            saveDataToFile(types,typefile)
        end
    end
end